/*文件共置（首页）*/
'use client'
import React, { useLayoutEffect, useState, useEffect } from "react";
import {
    Navbar,
    NavbarBrand,
    NavbarMenuToggle,
    NavbarMenuItem,
    NavbarMenu,
    NavbarContent,
    NavbarItem,
    Link,
    useDisclosure,
    Spacer, Spinner, Code, Switch,
} from "@nextui-org/react";
import { NoteIcon } from "@/app/assets/icons/NoteIcon";
import { useRouter } from "next/navigation";
import Profile from "@/app/pages/profile/Profile";
import './assets/css/customStyle.css'
import OnAuthenticatedNavbarContent from "@/app/components/home/onAuthenticatedNavbarContent";
import UnAuthenticatedNavbarContent from "@/app/components/home/unAuthenticatedNavbarContent";
import AuthModal from "@/app/components/auth/authModal";
import ExitLogin from "@/app/components/profile/exitLogin";
import HomeBody from "@/app/components/home/homeBody";
import { AuthenticationChecker } from "@/app/config/authenticationChecker";
import { BrowserRouter as Router } from 'react-router-dom';
import UserNavbarComponents from "@/app/components/home/UserNavbarComponents";
import GuestNavbarComponents from "@/app/components/home/GuestNavbarComponents";
import PubSub from 'pubsub-js'
import { MoonIcon, SunIcon } from "@nextui-org/shared-icons";
import theme from "tailwindcss/defaultTheme";
import { useTheme } from "next-themes";
import ThemeSwitchCom from "@/app/components/tools/ThemeSwitch";
import ProjectIntroModal from "@/app/components/modals/ProjectIntroModal";
import HelpCenterModal from "@/app/components/modals/HelpCenterModal";
import AboutUsModal from "@/app/components/modals/AboutUsModal";
import { BiAnchor } from "react-icons/bi";
/**
 * 入口页
 * @constructor
 */
export default function App() {
    /*路由*/
    const router = useRouter();

    /*Loading*/
    const [loading, setLoading] = useState(true);

    /*已登录过状态*/
    const [loginEd, setLoginEd] = useState(false);

    /*用户信息*/
    const [username, setUsername] = useState('');

    /*手机模式Menu状态*/
    const [isMenuOpen, setIsMenuOpen] = React.useState(false);

    /*顶部选项 --- 未登录*/
    const menuItems_unLogin = [
        "项目介绍",
        "帮助中心",
        "关于我们"
    ];

    /*顶部选项 --- 已登录*/
    const menuItems_inLogin = [
        "我的分享",
        "我的标签",
        "我的评论",
        "AI助手"
    ];

    const menuData = loginEd ? menuItems_inLogin : menuItems_unLogin;

    /*定义Dialog状态*/
    const { isOpen, onOpen, onOpenChange } = useDisclosure();
    const [isExit, setExit] = useState(false);
    /*Share State.*/
    const {
        isOpen: isOpenShare,
        onOpen: onOpenShare,
        onOpenChange: onOpenChangeShare
    } = useDisclosure()
    const {
        isOpen: isOpenNavbarClick,
        onOpen: onOpenNavbarClick,
        onOpenChange: onOpenChangeNavbarClick
    } = useDisclosure()
    const {
        isOpen: isOpenGuestNavbarClick,
        onOpen: onOpenGuestNavbarClick,
        onOpenChange: onOpenChangeGuestNavbarClick
    } = useDisclosure()

    /*已登录消息*/
    const [data, setData] = useState({
        title: '',
        message: ''
    });
    /*未登录消息*/
    const [dataGuest, setDataGuest] = useState({
        title: '',
        body: <></>,
    });

    /*界面加载完成事件*/
    useLayoutEffect(() => {
        /*登录验证*/
        async function fetchData() {
            const [authentication, username] = AuthenticationChecker();
            setLoading(false);//等待请求完毕再关闭Loading
            if (authentication) {
                setLoginEd(true)
                setUsername(username.toString());
            }
        }

        /*异步执行*/
        fetchData().then(r => {
        });
    }, [])

    // 添加对401事件的监听
    useEffect(() => {
        // 订阅AUTH_EXPIRED事件
        const authExpiredSubscription = PubSub.subscribe('AUTH_EXPIRED', (_, data) => {
            console.log('收到授权过期事件:', data.message);

            // 清除本地存储的用户状态
            if (loginEd) {
                setLoginEd(false);
                setUsername('');
            }

            // 如果用户当前在需要授权的页面，则重定向到首页
            if (window.location.pathname !== '/') {
                window.location.href = '/';
            } else {
                // 如果已经在首页，则打开登录modal
                onOpen();
            }
        });

        // 组件卸载时取消订阅
        return () => {
            PubSub.unsubscribe(authExpiredSubscription);
        };
    }, [loginEd, onOpen]);

    /*笔记搜索状态*/
    const [inSearch, setInSearch] = useState(false);

    // 添加Modal状态控制
    const {
        isOpen: isOpenProjectIntro,
        onOpen: onOpenProjectIntro,
        onOpenChange: onOpenChangeProjectIntro
    } = useDisclosure();

    const {
        isOpen: isOpenHelpCenter,
        onOpen: onOpenHelpCenter,
        onOpenChange: onOpenChangeHelpCenter
    } = useDisclosure();

    const {
        isOpen: isOpenAboutUs,
        onOpen: onOpenAboutUs,
        onOpenChange: onOpenChangeAboutUs
    } = useDisclosure();

    return (
        loading ?
            <div className={'flex justify-center h-screen items-center bg-white dark:bg-default-200'}>
                <Spinner label="加载ing...😵‍💫" color="primary" labelColor="primary" size={"lg"} />
            </div> :
            <div className={"flex flex-col h-screen"}>
                {/*主体NavBar*/}
                <Navbar
                    isBordered={true}
                    isBlurred={true}
                    isMenuOpen={isMenuOpen}
                    onMenuOpenChange={setIsMenuOpen}
                    className={`dark:bg-default-100`}
                >
                    {/*标题*/}
                    <NavbarContent className="sm:hidden pr-3" justify="start">
                        <NavbarMenuToggle aria-label={isMenuOpen ? "Close menu" : "Open menu"}
                            className="sm:hidden dark:text-white" />
                        <NavbarBrand>
                            <NoteIcon />
                            <p className="font-bold text-inherit ms-0.5 dark:text-white light:text-black ">Me Notes</p>
                        </NavbarBrand>
                    </NavbarContent>
                    {/*标杆*/}
                    <NavbarContent className={`hidden sm:flex gap-4`} justify="center">
                        <NavbarBrand>
                            <NoteIcon />
                            <p className="font-bold text-inherit ms-0.5 dark:text-white light:text-black ">Me Notes</p>
                        </NavbarBrand>
                        <Spacer x={0.5} />
                        {loginEd ? <>
                            <NavbarItem>
                                <Link color="foreground" href="/shares">
                                    我的分享
                                </Link>
                            </NavbarItem>
                            <NavbarItem>
                                <Link color={"foreground"} href="#" onPress={() => {
                                    handleNavbarClick('我的标签');
                                }}>
                                    我的标签
                                </Link>
                            </NavbarItem>
                            <NavbarItem>
                                <Link color="foreground" href="#" onPress={() => {
                                    handleNavbarClick('我的评论');
                                }}>
                                    我的评论
                                </Link>
                            </NavbarItem>
                            <NavbarItem className="relative flex items-center gap-1 border-2 border-primary rounded-full bg-gradient-to-r from-primary to-primary-600 text-white px-3 py-0 shadow-lg hover:shadow-primary/50 transition-all duration-300 overflow-hidden group">
                                {/* 发光背景效果 */}
                                <span className="absolute inset-0 bg-white/20 rounded-full animate-pulse"></span>

                                <BiAnchor size={20} className="text-white z-10 group-hover:rotate-12 transition-transform duration-300" />
                                <Link className="text-white font-bold z-10" color={"foreground"} href="/ai">
                                    AI助手
                                </Link>
                            </NavbarItem>
                        </> : <><NavbarItem>
                            <Link color="foreground" href="#" onPress={() => {
                                handleNavbarClick('项目介绍');
                            }}>
                                项目介绍
                            </Link>
                        </NavbarItem>
                            <NavbarItem>
                                <Link color={"foreground"} href="#" onPress={() => {
                                    handleNavbarClick('帮助中心');
                                }}>
                                    帮助中心
                                </Link>
                            </NavbarItem>
                            <NavbarItem>
                                <Link color="foreground" href="#" onPress={() => {
                                    handleNavbarClick('关于我们');
                                }}>
                                    关于我们
                                </Link>
                            </NavbarItem>
                        </>
                        }
                    </NavbarContent>


                    {/*头像部分*/}
                    {loginEd ?
                        /*已登录头像部分*/
                        <OnAuthenticatedNavbarContent username={username} isExit={isExit} setExit={setExit}
                            setInSearch={setInSearch} />
                        :
                        /*无登录头像部分*/
                        <UnAuthenticatedNavbarContent onOpen={onOpen} />
                    }
                    {/*手机模式 Menu 列表*/}
                    <NavbarMenu>
                        {menuData.map((item, index) => (
                            <NavbarMenuItem key={`${item}-${index}`}>
                                {item === "我的分享" ? (
                                    <Link
                                        className="w-full"
                                        color="foreground"
                                        href="/shares"
                                        size="lg"
                                    >
                                        {item}
                                    </Link>
                                ) : (
                                    <Link
                                        className="w-full"
                                        color="foreground"
                                        href="#"
                                        size="lg"
                                        onPress={() => {
                                            handleNavbarClick(item);
                                        }}
                                    >
                                        {item}
                                    </Link>
                                )}
                            </NavbarMenuItem>
                        ))}
                    </NavbarMenu>
                    {/*登录Dialog*/}
                    <AuthModal isOpen={isOpen} onOpenChange={onOpenChange} />
                </Navbar>
                {/*内容区域*/}
                {
                    loginEd ?
                        /*LoginEd*/
                        <Router>
                            <Profile inSearch={inSearch} setInSearch={setInSearch} />
                        </Router>
                        :
                        /*Don't Login*/
                        <HomeBody onOpen={onOpen} />
                }
                {/*退出登录Modal*/}
                <ExitLogin isExit={isExit} setExit={setExit} />
                {/*我的标签和我的评论组件*/}
                <UserNavbarComponents isOpenNavbarClick={isOpenNavbarClick}
                    onOpenChangeNavbarClick={onOpenChangeNavbarClick} data={data} />
                <GuestNavbarComponents isOpenGuestNavbarClick={isOpenGuestNavbarClick}
                    onOpenChangeGuestNavbarClick={onOpenChangeGuestNavbarClick} data={dataGuest} />

                {/* 添加Modal组件 */}
                <ProjectIntroModal
                    isOpen={isOpenProjectIntro}
                    onOpenChange={onOpenChangeProjectIntro}
                />
                <HelpCenterModal
                    isOpen={isOpenHelpCenter}
                    onOpenChange={onOpenChangeHelpCenter}
                />
                <AboutUsModal
                    isOpen={isOpenAboutUs}
                    onOpenChange={onOpenChangeAboutUs}
                />
            </div>
    );

    /*点击时间*/
    function handleNavbarClick(item: any) {
        switch (item) {
            case '我的分享':
                if (loginEd) {
                    onOpenShare();
                    /**
                     * 关闭Item
                     */
                    setIsMenuOpen(false);
                }
                break;

            case '我的标签':
                if (loginEd) {
                    router.push('/tags');
                    setIsMenuOpen(false);
                }
                break;

            case 'AI助手':
                if (loginEd) {
                    router.push('/ai');
                    setIsMenuOpen(false);
                }
                break;

            case '我的评论':
                if (loginEd) {
                    router.push('/comments');
                    setIsMenuOpen(false);
                }
                break;

            case '关于我们':
                //打开关于我们Modal
                onOpenAboutUs();
                setIsMenuOpen(false);
                break;

            case '项目介绍':
                //打开项目介绍Modal
                onOpenProjectIntro();
                setIsMenuOpen(false);
                break;

            case '帮助中心':
                //打开帮助中心Modal
                onOpenHelpCenter();
                setIsMenuOpen(false);
                break;

            default:
                //指定消息

                break;
        }
    }
}